<template>
  <div class="log-container">
    <div class="log-header">
      <h2>系统操作日志</h2>
      <div class="log-filter">
        <el-input
          v-model="searchQuery"
          placeholder="输入关键字搜索日志内容"
          clearable
          prefix-icon="el-icon-search"
          style="width: 300px"
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
        />
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          @change="handleDateChange"
          style="width: 250px"
        />
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button type="danger" icon="el-icon-delete" @click="batchDelete">批量删除</el-button>
      </div>
    </div>

    <el-table
      :data="filteredLogs"
      style="width: 100%"
      border
      stripe
      height="calc(100vh - 260px)"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column
        label="序号"
        width="80"
        align="center"
        type="index"
        :index="indexMethod">
      </el-table-column>
      <el-table-column prop="logTime" label="时间" width="180" align="center">
        <template slot-scope="scope">
          {{ formatDate(scope.row.logTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="log" label="日志内容" min-width="250">
        <template slot-scope="scope">
          <div class="log-content">
            <span class="log-main">{{ scope.row.log }}</span>
            <span class="log-ip">IP：{{ scope.row.ip }}</span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="username" label="用户" width="120" align="center"></el-table-column>
      <el-table-column prop="method" label="方法" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="getMethodType(scope.row.method)" size="small">{{ scope.row.method }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型" width="150" align="center"></el-table-column>
    </el-table>

    <div class="log-pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        background
      ></el-pagination>
    </div>
  </div>
</template>

<script>
import { sysLog ,deleteLog} from '@/api/SysLog/syslog'
export default {
  name: 'LogView',
  data() {
    return {
      logs: [],
      filteredLogs: [],
      loading: false,
      searchQuery: '',
      dateRange: null,
      selectedIds: [], // 存储选中的日志ID
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      }
    }
  },
  watch: {
    'pagination.currentPage': {
      handler() {
        this.fetchLogs()
      }
    },
    'pagination.pageSize': {
      handler() {
        this.fetchLogs()
      }
    }
  },
  created() {
    this.fetchLogs()
  },
  methods: {
    indexMethod(index) {
      // 从1开始自增
      return index + 1;

    },
    async fetchLogs() {
      this.loading = true
      try {
        const res = await sysLog({
          page: this.pagination.currentPage,
          size: this.pagination.pageSize,
          search: this.searchQuery,
          startDate: this.dateRange ? this.dateRange[0] : null,
          endDate: this.dateRange ? this.dateRange[1] : null
        })

        this.filteredLogs = res.data.list || res.data
        this.pagination.total = res.data.total || res.data.length
      } catch (error) {
        console.error('获取日志失败:', error)
        this.$message.error('获取日志失败')
      } finally {
        this.loading = false
      }
    },
    handleSearch() {
      this.pagination.currentPage = 1
      this.fetchLogs()
    },
    handleDateChange() {
      this.pagination.currentPage = 1
      this.fetchLogs()
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
    },
    handleCurrentChange(val) {
      this.pagination.currentPage = val
    },
    handleSelectionChange(selection) {
      this.selectedIds = selection.map(item => item.id)
    },
    async batchDelete() {
      if (this.selectedIds.length === 0) {
        this.$message.warning('请至少选择一条日志')
        return
      }

      try {
        const confirmResult = await this.$confirm(
          `确定要删除选中的 ${this.selectedIds.length} 条日志吗？`,
          '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        if (confirmResult === 'confirm') {
          // 确保传递的是数字数组（如果后端需要）
          const idsToDelete = this.selectedIds.map(id => Number(id))

          const res = await deleteLog(idsToDelete)

          if (res.code === 20000) {
            this.$message.success('删除成功')
            this.fetchLogs()
            this.selectedIds = [] // 清空选中状态
          } else {
            this.$message.error(res.msg || '删除失败')

          }
        }
      } catch (error) {
        console.error('删除失败:', error)
        if (error !== 'cancel') { // 避免取消操作也显示错误
          this.$message.error('删除失败: ' + (error.response?.data?.message || error.message))
        }
      }
    },
    formatDate(date) {
      return date
    },
    getMethodType(method) {
      const types = {
        'GET': 'primary',
        'POST': 'success',
        'PUT': 'warning',
        'DELETE': 'danger'
      }
      return types[method] || 'info'
    }
  }
}
</script>

<style scoped>
.log-container {
  margin: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  overflow: hidden;
}

.log-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.log-header h2 {
  margin: 0;
  font-size: 1.2rem;
  color: #333;
}

.log-filter {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.log-content {
  line-height: 1.5;
}

.log-main {
  display: block;
  font-weight: 500;
}

.log-ip {
  font-size: 12px;
  color: #999;
}

.log-pagination {
  margin-top: 20px;
  text-align: right;
  background: #fff;
  padding: 10px;
  border-radius: 4px;
  border: 1px solid #eee;
}
</style>
